package etc.netty.client;

import com.dmz.test.etc.domain.MsgClazz;
import com.dmz.test.etc.netty.attr.ChannelAttrs;
import com.dmz.test.etc.service.ServerService;
import com.dmz.test.etc.utils.SpringUtil;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;


/**
 * @author lee
 */
@Slf4j
public class ClientHandler extends ChannelInboundHandlerAdapter {

    // 引用回NettyServerBHandler中的channel，用于发送回复给客户端A
    private final Channel serverChannel;

    public ClientHandler(Channel serverChannel) {
        this.serverChannel = serverChannel;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        // 当客户端与服务器建立连接后，发送消息给服务器
        //String message = "Hello, Netty Server!";
        log.info("本服务启动的客户端连接到:{}", ctx.channel().remoteAddress().toString());
        super.channelActive(ctx);
        //ctx.writeAndFlush(message);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        int forward = serverChannel.attr(ChannelAttrs.forward).get();
        log.info("本服务启动的客户端接收到消息回应===================={}==================================", forward);
        // 接收服务器的响应消息并打印
        byte[] data = (byte[]) msg;
        log.info("接收到的报文: {}", msg);
        ServerService serverService = SpringUtil.getBean(ServerService.class);
        //监听C回写A
        if(forward == 1) {
            MsgClazz process = serverService.encrypt(data, serverChannel);
            log.info("7回复ETC===============================================");
            serverChannel.writeAndFlush(process.getData());
        }else {
            //监听A回写C
            if(forward == 2) {
                MsgClazz process = serverService.decrypt(data, serverChannel);
                serverChannel.writeAndFlush(process.getData());
            }
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        // 处理异常，打印错误信息并关闭连接
        log.error("server client close exception", cause);
        ctx.close();
    }
}